// PWMdemo.c
//
// small sample explains setup for running PWM in both 8-bit
// and 10-bit modes

#include <16F690.h>
#include <STDLIB.h>
#fuses INTRC_IO,NOWDT,NOPROTECT,NOMCLR,NOBROWNOUT,NOIESO,NOFCMEN 
#use delay(clock=8000000)

long i;     // variable to hold 10-bit PWM value
int j;      // variable to hold 8-bit PWM value
int k;      // scratchpad variable

void main(void){
	
	setup_ccp1(CCP_PWM);		//Enable Pulse Width Modulator Mode

/*  
    Timer_2 in the PIC is what generates the PWM output. Here is an 
    explanation of the setup_timer_2(mode, period, postscale) 
    function call in the code below.
    
    In this example clock = 8MHz, mode = T2_DIV = 1, and period = 255.
    PWM cycle time will be 
    1/clock     * 4 * t2div * (period+1). For an 8 MHz clock,
    (1/8000000) * 4 * 1     * 256 = .000128 sec = 128 microsec = 7812Hz
    
    If this is used to control a motor, the PWM frequency of 7.8kHz will
    be annoying to many people. It would probably be better to add an
    external clock oscillator at 20MHz to push the PWM accoustics toward
    the ultrasonic range (19.5kHz with a 20MHz clock).
    
    setup_timer_2() takes three parameters:
    mode - T2_DIV (see above), can be T2_DIV_BY_1, T2_DIV_BY_4, or T2_DIV_BY_16
    period - a value which will represent the maximum PWM value in 8-bit
        mode and the maximum value/4 in 10 bit mode. Lowering this value
        increases the PWM frequency and decreases the resoloution. 
    postscale - a multiplier which only has an effect if Timer_2 is being used
        as a time-base for an interrupt generator. It has no effect on PWM.
    
    There are probaby only a few PWM applications which would require a
    different configuration of setup_timer_2() than the one below.

*/
    setup_timer_2(T2_DIV_BY_1, 255, 1); 


// This while loop shows 10-bit mode. Variable containing PWM value must
// be a long. This loop takes 4 times as long to run as the loop below
// because it has 4 times the resolution.
    
	  while(1){
		  
        for (i=0; i< 1024; i++){

// calling set_pwm1_duty() with a long causes compiler to use 10-bit mode
            set_pwm1_duty((long)i); 
									
			 delay_ms(10);
		}

		for (i=1023; i>0; i--){
			 set_pwm1_duty(i);
			 delay_ms(10);
		}
    }
} //end of main()

/*

// This while loop shows 8-bit mode. Variable containing PWM value
// must be an int.
	
    while(1){

        for (j=0; j<255; j++){

// calling set_pwm1_duty() with an int causes compiler to use 8-bit mode
        set_pwm1_duty(j);

            delay_ms(10);
        }

        for (j=255; j>0; j--){
            set_pwm1_duty(j);
            delay_ms(10);
        }
    }
} //end of main()

*/

